package tech.summerly.weather.component.view

import android.content.Context
import android.support.design.widget.BottomSheetBehavior
import android.support.design.widget.CoordinatorLayout
import android.support.v4.widget.NestedScrollView
import android.util.AttributeSet
import android.view.View
import android.view.animation.AnimationUtils
import androidx.core.view.isGone
import androidx.core.view.isNotEmpty
import androidx.core.view.isVisible
import com.google.android.exoplayer2.ui.PlayerView
import kotlinx.android.synthetic.main.content_weather_alert.view.*
import kotlinx.android.synthetic.main.sheet_forecast_2.view.*
import kotlinx.android.synthetic.main.view_weather.view.*
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.launch
import tech.summerly.weather.R
import tech.summerly.weather.component.adapter.DailyForecastAdapter
import tech.summerly.weather.component.adapter.LifeStyleAdapter
import tech.summerly.weather.data.WeatherRepository
import tech.summerly.weather.data.bean.Alert
import tech.summerly.weather.data.bean.Forecast
import tech.summerly.weather.data.bean.HourlyForecast
import tech.summerly.weather.data.bean.RealTime
import tech.summerly.weather.data.remote.CaiYunService
import tech.summerly.weather.model.Region
import tech.summerly.weather.util.*
import java.util.*


/**
 * the view to display a weather
 */
@Deprecated("emmmm , 不好看，换一个")
class WeatherView : CoordinatorLayout {
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)


    private val bottomSheetBehavior: BottomSheetBehavior<NestedScrollView>

    private val bottomSheetCallback = object : BottomSheetBehavior.BottomSheetCallback() {
        override fun onSlide(bottomSheet: View, slideOffset: Float) {
            val invert = 1 - slideOffset
            indicator.alpha = invert
            bottomSheet.alpha = slideOffset

            layoutAlert.alpha = invert
        }

        override fun onStateChanged(bottomSheet: View, newState: Int) {

        }
    }

    val playerView: PlayerView get() = this.playerViewI

    init {
        View.inflate(context, R.layout.view_weather, this)
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetContainer)
        bottomSheetBehavior.setBottomSheetCallback(bottomSheetCallback)
        val animation = AnimationUtils.loadAnimation(context, R.anim.anim_breath)
        indicator.startAnimation(animation)
    }

    private var mRealTime: RealTime? = null
    private var mForecast: Forecast? = null

    fun displayWeather(region: Region) {
        //set realtime weather
        launch(UI) {
            try {
                val weather = WeatherRepository.getRealtimeWeather(region)
                mRealTime = weather
                showRealtimeWeather(weather)
            } catch (e: Exception) {
                e.printStackTrace()
                toast(e.message ?: "出错")
            }
        }
        //set forecast information
        launch(UI) {
            try {
                val weather = WeatherRepository.getForecastWeather(region)
                mForecast = weather
                showForecast(weather)
            } catch (e: Exception) {
                toast(e.message ?: "出错")
            }
        }
        //show city name
        textCity.text = region.name
        val today = today()
        textDate.text = "%d月%d日".format(today[Calendar.MONTH] + 1, today[Calendar.DAY_OF_MONTH])
    }

    //显示实时信息
    private fun showRealtimeWeather(realTime: RealTime) {
        log { realTime }
        textTemperature.text = "%s°".format(realTime.temperature.toIntString())
        textQuality.text = string(R.string.template_aqi).format(realTime.pm25)
        textSky.text = realTime.getSkyConString()
        imageSky.setImageResource(CaiYunService.SkyCon.getSkyIcon(realTime.skycon))
        setBackgroundColor(realTime.getSkyCon().getBackgroundColor())
    }

    //显示预报
    private fun showForecast(forecast: Forecast) {
        log { forecast }
        showHourlyForecast(forecast.hourly)
        showDailyForecast(forecast)
        showAlert(forecast.alert)
        showLifeStyle(forecast)
    }

    private fun showLifeStyle(forecast: Forecast) {
        val adapter = LifeStyleAdapter()
        listLifeStyle.adapter = adapter
        adapter.setData(forecast.daily)
    }

    private fun showAlert(alerts: List<Alert>?) {
        if (layoutAlert.isNotEmpty()) {
            layoutAlert.removeAllViews()
        }
        alerts ?: return
        alerts.forEach { alert ->
            val alertView = View.inflate(context, R.layout.content_weather_alert, layoutAlert)
            alertView.setOnclickListenerSafely {
                toast(alert.description)
            }
            alertView.textStatus.text = "%s:%s".format(alert.status, alert.description)
        }
    }


    private fun showDailyForecast(forecast: Forecast) {
        listDaily.adapter = DailyForecastAdapter(forecast.daily)
    }

    private fun showHourlyForecast(hourly: HourlyForecast) {
        val colorPrimary = color(R.color.color_primary_dark)
//        chartHourly.reset()
//        chartHourly.setLabelsColor(colorPrimary)
//        val temperature = hourly.temperature.take(24)
//        val dateTime = temperature.map { it.datetime }.toTypedArray()
//        dateTime.forEachIndexed { index, value ->
//            if (index % 3 != 0) {
//                dateTime[index] = ""
//            } else {
//                dateTime[index] = value.substringAfterLast(" ")
//            }
//        }
//        val dataset = LineSet(dateTime, temperature.map { it.value }.toFloatArray())
//        dataset.setColor(colorPrimary)
//                .setDotsColor(colorPrimary)
//                .setThickness(4f)
//                .setSmooth(SettingsActivity.isChartLineSmooth())
//
//        chartHourly.addData(dataset)
//        chartHourly.setYLabels(AxisRenderer.LabelPosition.OUTSIDE)
//                .setLabelsFormat(DecimalFormat("#"))
//                .setXAxis(false)
//                .show()
    }

    fun setLifeStyle(show: Boolean) {
        if (show) {
            cardLifeStyle.isVisible = true
        } else {
            cardLifeStyle.isGone = true

        }
    }

    override fun isPointInChildBounds(child: View?, x: Int, y: Int): Boolean {
        //即使触摸点在子 view 外，也让子 view 的 behavior 响应触摸事件
        return true
    }


    fun setOnLiveWeatherIconClick(listener: ((View) -> Unit)?) {
        imageLiveWeather.setOnClickListener(listener)
    }


    fun onBackPressed(): Boolean {
        if (bottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED) {
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
            return true
        }
        return false
    }

}